<template>
  <div class="message-list">
    <div class="list-header">
      <h3>访客列表</h3>
      <el-tag type="info" size="small">{{ adjustedOnline }}人在线</el-tag>
    </div>

    <el-scrollbar height="calc(100vh - 140px)">
      <!-- 客户列表 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-else-if="customersData.length" class="list-section">
        <div class="section-title">
          <span>客户列表</span>
          <el-tag size="small" type="success">{{
            customersData.length
          }}</el-tag>
        </div>
        <el-menu
          @select="handleSelect"
          class="visitor-menu"
          :default-active="activeUser"
        >
          <el-menu-item
            v-for="user in customersData"
            :key="user.username"
            :index="user.username"
            class="visitor-item"
            :class="{ 'highlight': highlightedVisitor === user.username }"
            @click="handleVisitorClick(user)"
          >
            <div class="visitor-info">
              <el-avatar
                :size="36"
                src="https://qy-kefu.oss-cn-beijing.aliyuncs.com/img/客户来访.png"
              />
              <div class="visitor-detail">
                <span class="visitor-name">{{ user.displayName }}</span>
                <span v-if="user.hasNewMessage" class="new-message-dot"></span>

                <span class="visitor-time"
                  >上线时间：{{ user.lastTime || formatTime(new Date()) }}</span
                >
              </div>

              <el-badge
                v-if="user.unreadCount > 0"
                :value="user.unreadCount"
                class="unread-badge"
              />
              <el-tag
                size="small"
                :type="user.status === 'online' ? 'success' : 'info'"
                effect="plain"
                class="status-tag"
              >
                {{ user.status === "online" ? "在线" : "离线" }}
              </el-tag>
            </div>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 客服列表 -->
        <!-- <div v-if="staffs.length" class="list-section">
          <div class="section-title">
            <span>客服列表</span>
            <el-tag size="small" type="primary">{{ staffs.length }}</el-tag>
          </div>
          <el-menu
            @select="handleSelect"
            class="visitor-menu"
            :default-active="activeUser"
          >
            <el-menu-item
              v-for="user in staffs"
              :key="user.username"
              :index="user.username"
              class="visitor-item"
              @click="handleVisitorClick(user)"
            >
              <div class="visitor-info">
                <el-avatar
                  :size="36"
                  src="https://qy-kefu.oss-cn-beijing.aliyuncs.com/img/客服.png"
                />
                <div class="visitor-detail">
                  <span class="visitor-name">{{
                    user.displayName || user.username
                  }}</span>
                  <span class="visitor-time"
                    >上线时间：{{ user.lastTime || formatTime(new Date()) }}</span
                  >
                </div>
                <el-tag
                  size="small"
                  :type="user.status === 'online' ? 'success' : 'info'"
                  effect="plain"
                  class="status-tag"
                >
                  {{ user.status === "online" ? "在线" : "离线" }}
                </el-tag>
              </div>
            </el-menu-item>
          </el-menu>
        </div> -->

      <el-empty v-if="!users?.length" description="暂无访客" />
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import {
  defineEmits,
  defineProps,
  computed,
  ref,
  watch,
  defineExpose,
} from "vue";
import request from "@/utils/request";
import { useVisitorStore } from "@/store/modules/visitor";
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();

interface User {
  username: string;
  lastTime?: string;
  status?: string;
  realName?: string;
  unreadCount?: number;
}

const props = defineProps<{
  users?: User[];
  pageNum: number;
}>();

const emit = defineEmits(["select", "highlight-visitor", "update-new-message-status"]);

const activeUser = ref("");

const visitorStore = useVisitorStore();

const getAvatarUrl = (username: string) => {
  if (username.length >= 10) {
    return "https://qy-kefu.oss-cn-beijing.aliyuncs.com/img/客户来访.png";
  }
  return "https://qy-kefu.oss-cn-beijing.aliyuncs.com/img/客服.png";
};

const formatUsername = async (username: string) => {
  if (username.length >= 10) {
    try {
      // 1. 先调用 getFinger 接口检查是否有真实姓名
      const fingerResponse = await request.get("/api/v1/visitor/getFinger", {
        params: {
          digitalFingerprint: username,
        },
      });

      // 如果有真实姓名，直接返回
      if (fingerResponse.code === "200" && fingerResponse.data?.realName) {
        return fingerResponse.data.realName;
      }

      // 2. 如果没有真实姓名，则使用原有的 updateOrInsert 逻辑
      const response = await request({
        url: "/api/v1/visitor/updateOrInsert",
        method: "post",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        data: new URLSearchParams({
          digitalFingerprint: username,
          realName: "",
        }),
      });

      if (response.data?.realName) {
        return response.data.realName;
      }

      // 3. 如果都没有真实姓名，使用默认的访客编号
      const lastFourDigits = username.slice(-4);
      return `访客_${lastFourDigits}`;
    } catch (error) {
      console.error("获取访客信息失败:", error);
      const lastFourDigits = username.slice(-4);
      return `访客_${lastFourDigits}`;
    }
  }
  return username;
};

// const loading = ref(true);
const customersData = ref<User[]>([]);

const loadCustomers = async () => {
  try {
    const customerList =
      props.users?.filter((user) => user.username.length >= 10) || [];

    const formattedCustomers = await Promise.all(
      customerList.map(async (user) => ({
        ...user,
        displayName: await formatUsername(user.username),
        hasNewMessage: false,
        unreadCount: user.unreadCount !== undefined ? user.unreadCount : 0,
      }))
    );

    customersData.value = formattedCustomers;
    console.log("________________________________________");
    console.log(customersData.value);
    console.log("________________________________________");

  } catch (error) {
    console.error("加载访客列表失败:", error);
  }
};

// 暴露 loadCustomers 方法给父组件
defineExpose({
  loadCustomers,
});

watch(() => props.users, loadCustomers, { immediate: true });

const staffs = computed(
  () =>
    props.users
      ?.filter((user) => user.username.length < 10)
      .map((user) => ({
        ...user,
        displayName: user.username,
      })) || []
);

  const totalOnline = computed(
    () => props.users?.filter((user) => user.status === "online").length || 0
  );
    // 调整后的在线人数
    const adjustedOnline = computed(() =>
      totalOnline.value > 0 ? totalOnline.value - 1 : totalOnline.value + 1
    );

const handleSelect = async (key: string) => {
  console.log("选中的用户:", key);
  activeUser.value = key;

  const selectedUser = customersData.value.find(
    (user) => user.username === key
  );

  if (selectedUser) {
    // 调用更新消息状态的接口
    try {
      await request.put(`api/v1/message/updateStatus/${selectedUser.username}`);
      // 更新徽章的值为0
      selectedUser.unreadCount = 0;

      visitorStore.setSelectedVisitor({
        username: selectedUser.username,
        digitalFingerprint: selectedUser.username,
        lastTime: selectedUser.lastTime,
        status: selectedUser.status,
      });
      emit("select", selectedUser.username);
    } catch (error) {
      console.error("更新消息状态失败:", error);
    }
  }
};

const formatTime = (date: Date) => {
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
};


</script>

<style lang="scss" scoped>
@mixin text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-list {
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .list-header {
    padding: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ebeef5;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .list-section {
    margin-bottom: 16px;

    .section-title {
      padding: 12px 16px 8px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #909399;
      font-size: 13px;
    }
  }

  .visitor-menu {
    border-right: none;

    .visitor-item {
      padding: 12px 16px;
      height: auto;
      line-height: 1.5;

      &:hover {
        background-color: #f5f7fa;
      }

      &.is-active {
        background-color: #ecf5ff;

        .visitor-name {
          color: #409eff;
        }
      }
    }
  }

  .visitor-info {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
  }

  .visitor-detail {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .visitor-name {
    font-size: 14px;
    color: #303133;
    margin: 0;
    @include text-ellipsis;
  }

  .visitor-time {
    font-size: 12px;
    color: #909399;
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .status-tag {
    flex-shrink: 0;
  }
}

.visitor-item.highlight {
  background-color: #f0f9eb; /* 高亮背景色 */
}

.new-message-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: red;
  border-radius: 50%;
  margin-left: 5px;
}

.unread-badge {
  margin-left: 5px;
}
</style>
